<?php
/**
 * Notes:
 * User: Administrator
 * Date: 2020/9/27
 * Time: 18:15
 * ${PARAM_DOC}
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 */

namespace App\Http\model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Dotenv\Exception;
use App\Http\model\Poll;
use App\Http\Controllers\PollController;
use Illuminate\Support\Facades\Log;

class Send extends Model
{
    /**
     * [根据erp传过来的参数修改商城的发货状态】
     * @param $OrderID
     * @param $fields
     * @return mixed
     */
    public function syncChangesModel($request)
    {
        $OrderID = $request['PlatOrderNo'];//订单号
        Log::info('===发货订单号===' . $OrderID);
        Log::info('===LogisticName===' . $request['LogisticName']);
        $kname = DB::table('pollinfo')->where('kname', $request['LogisticName'])->first();
        $kname = json_decode(json_encode($kname), true);

        Log::info('===发货类型===' . $request['SendType']);
//        dd($request['SendType']);
        if ($request['SendType'] == 'JH_03') {
            //吉客云 线下配送
            DB::beginTransaction();
            try {
                $updata = DB::table('orderdetail')
                    ->where('OIcode', $OrderID)
                    ->update([
                        'expressname' => '线下配送',
                        'expressnum' => '线下配送',
                        'exprestate' => 1
                    ]);
                Log::info('===jh03detail发货结果===' . $updata);
                //插入物流信息表
                $insert['itemcode'] = $OrderID;//订单号
                $insert['nu'] = '线下配送';//运单号

                if ($updata == 1 /*&& $count < 1*/) {
                    $res2 = DB::table('poll')->insertGetId($insert);
                }
                //如果子订单都发货那就修改主订单为8 ====已发货
                Send::orderexpres($OrderID);

                if ($updata && $res2 > 0) {
                    DB::commit();
                } else {
                    DB::rollBack();
                }
                return $updata;
            } catch (\Exception $e) {
                DB::rollback();//事务回滚
                Log::error("jh03更新错误原因" . "=============" . $e->getMessage());
                //$result = $e->getCode();
            }

        } else {
            if (empty($kname['kname'])) {
                return response()->json(['code' => '40000', 'message' => 'System Error', 'subcode' => 'GSE.SYSTEM_ERROR', 'submessage' => '快递公司名称被你吃了啊']);
            } else {
                Log::info('===快递别名===' . $request['LogisticName']);
                $companycode = $kname['kcode'];//快递编号
                $detailexpressname = $kname['kname'];//快递名称
                $number = $request['LogisticNo'];//运单号
                Log::info('===快递编号===' . $companycode);
                Log::info('===快递名称===' . $detailexpressname);
                Log::info('===运单号===' . $number);
                DB::beginTransaction();
                try {
                    $updata = DB::table('orderdetail')
                        ->where('OIcode', $OrderID)
                        ->update([
                            'expressname' => $detailexpressname,
                            'expressnum' => $number,
                            'exprestate' => 1
                        ]);
                    Log::info('===detail发货结果===' . $updata);
                    //插入物流信息表
                    $insert['itemcode'] = $OrderID;//订单号
                    $insert['nu'] = $number;//运单号

                    if ($updata == 1 /*&& $count < 1*/) {
                        $res2 = DB::table('poll')->insertGetId($insert);
                    }
                    //请求快递100订阅接口
                    Send::GetPoll($companycode, $number,env('CALLBACKURL'));

                    //如果子订单都发货那就修改主订单为8 ====已发货
                    Send::orderexpres($OrderID);

                    if ($updata && $res2 > 0) {
                        DB::commit();
                    } else {
                        DB::rollBack();
                    }
                    return $updata;
                } catch (\Exception $e) {
                    DB::rollback();//事务回滚
                    Log::error("更新错误原因" . "=============" . $e->getMessage());
                    //$result = $e->getCode();
                }
            };
        }

    }


    /**
     * @param $company 快递公司编码
     * @param $number 快递单号
     * @param $callback 快递去100回调地址
     */
    public static function GetPoll($company, $number, $callback)
    {
        Log::info("开始调用物流接口==========" . date('Y-/m/d H:i:s', time()));
        //参数设置
        $key = env('KEY');     //客户授权key
        $param = array(
            'company' => $company,             //快递公司编码
            'number' => $number,      //快递单号
            'from' => '',                     //出发地城市
            'to' => '',                       //目的地城市
            'key' => $key,                    //客户授权key
            'parameters' => array(
                'callbackurl' => $callback,        //回调地址
                'salt' => '',                 //加密串
                'resultv2' => '1',            //行政区域解析
                'autoCom' => '0',             //单号智能识别
                'interCom' => '0',            //开启国际版
                'departureCountry' => '',     //出发国
                'departureCom' => '',         //出发国快递公司编码
                'destinationCountry' => '',   //目的国
                'destinationCom' => '',       //目的国快递公司编码
                'phone' => ''                 //手机号
            )
        );

        //请求参数
        $post_data = array();
        $post_data["schema"] = 'json';
        $post_data["param"] = json_encode($param);
        $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址

        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";     //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
//        echo '请求参数<br/>' . $post_data;

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result);
        $data = json_decode($data);
        Log::info("结束调用物流接口==========" . date('Y-/m/d H:i:s', time()));
        Log::info('订阅结果:' . json_encode($data));
//        echo '<br/><br/>返回数据<br/>';
//        echo var_dump($data);
    }

    public function orderexpres($OIcode)
    {
        Log::info('===发货子单号===' . $OIcode);

        $code = DB::table('orderdetail')->select('OrderCode')->where('OIcode', $OIcode)->first();
        $code = json_decode(json_encode($code), true);
        Log::info('===发货主单号===' . $code['OrderCode']);

        $expressstate = DB::table('orderdetail')->select('exprestate')->where('OrderCode', $code['OrderCode'])->get();
        $expressstate = json_decode(json_encode($expressstate), true);

        foreach ($expressstate as $item) {
            if ($item['exprestate'] == 1) {
                $value[]['a'] = ($item['exprestate']);

            } else {
                $array[]['b'] = ($item['exprestate']);
            };
        }
        Log::info('===物流信息===' . 1);

        if (empty($array)) {
            $updorders = DB::table('orders')->where('Code', $code['OrderCode'])->update(['Status' => 8]);
            Log::info('主订单发货状态修改结果:' . $updorders);
        }
    }


}